package com.tes;

import java.util.ArrayList;
import java.util.List;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.camera.ZoomCamera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import com.tes.dao.HighScoreDAO;
import com.tes.model.HighScore;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;

public class SplashScreen extends BaseGameActivity {

	// screen size
	static final int CAMERA_WIDTH = 480;
	static final int CAMERA_HEIGHT = 320;

	// splash time
	static final float TIME_SPLASH = 4;

	// camera
	private Camera mCamera;

	// backgroud
	private BitmapTextureAtlas tBackground;
	private TextureRegion mBackground;

	// loading
	private BitmapTextureAtlas tLoading;
	private TextureRegion mLoading;

	// check if load finish
	private boolean isResourceLoad = false;

	// load resource
	private boolean loadFont = false;
	private boolean loadTexture = false;
	private boolean loadLevel = false;

	// Load manual setting yang ada di-Andengine
	@Override
	public Engine onLoadEngine() {
		this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE,
				new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT),
				this.mCamera));
	}

	// Load semua gambar berserta font style yang ada ditiap2 folder (resource)
	@Override
	public void onLoadResources() {
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");

		tBackground = new BitmapTextureAtlas(512, 512,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		mBackground = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				tBackground, this, "splashscreen.png", 0, 0);

		tLoading = new BitmapTextureAtlas(128, 128,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		mLoading = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				tLoading, this, "loading.png", 0, 0);

		// Load background triangle & loading bulat
		mEngine.getTextureManager().loadTextures(tBackground, tLoading);
	}

	@Override
	public Scene onLoadScene() {
		Scene mScene = new Scene();

		// Dibagi 2 karena layar/screen landscape ukuran 480&320 scale 1:2
		// (asalnya 960&640)
		final Sprite sBackground = new Sprite(
				(CAMERA_WIDTH - mBackground.getWidth()) / 2,
				(CAMERA_HEIGHT - mBackground.getHeight()) / 2, mBackground);
		// Menempelkan gambar pada scene (Saya lebih menyebutnya sebagai
		// LinearLayout/Container :)
		mScene.attachChild(sBackground);

		final Sprite sLoading = new Sprite(
				(CAMERA_WIDTH - mLoading.getWidth()) / 2, CAMERA_HEIGHT - 100,
				mLoading);
		sLoading.setScale(1.5f);
		mScene.attachChild(sLoading);

		IUpdateHandler iHandler = new IUpdateHandler() {
			float time = 0;

			@Override
			public void reset() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onUpdate(float pSecondsElapsed) {
				time += pSecondsElapsed;
				if (isResourceLoad && time >= TIME_SPLASH) {
					Intent intent = new Intent(SplashScreen.this, Menu.class);
					startActivity(intent);
					SplashScreen.this.finish();
				} else {
					sLoading.setRotation(sLoading.getRotation() + 5f);

					if (!loadFont) {
						loadFont = loadFont();
					} else if (!loadTexture) {
						loadTexture = loadTexture();
					} else if (!loadLevel) {
						loadLevel = loadLevel();
						loadHighScore();
					} else {
						isResourceLoad = true;
					}
				}
			}
		};

		mScene.registerUpdateHandler(iHandler);

		return mScene;
	}

	@Override
	public void onLoadComplete() {
		isResourceLoad = true;
	}

	protected boolean loadFont() {
		// camera
		GameResource.zoomCamera = new ZoomCamera(0, 0, CAMERA_WIDTH,
				CAMERA_HEIGHT);
		GameResource.camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);

		// set path
		FontFactory.setAssetBasePath("font/");

		// chiller
		GameResource.tFontChiller = new BitmapTextureAtlas(256, 256,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		GameResource.mFontChiller = FontFactory.createFromAsset(
				GameResource.tFontChiller, this, "CHILLER.ttf", 28, true,
				Color.RED);

		// quartz
		GameResource.tFontQuartz = new BitmapTextureAtlas(128, 128,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		GameResource.mFontQuartz = FontFactory.createFromAsset(
				GameResource.tFontQuartz, this, "QuartzMS.ttf", 22, true,
				Color.RED);

		// ocraext
		GameResource.tFontOCRAExt = new BitmapTextureAtlas(128, 128,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		GameResource.mFontOCRAExt = FontFactory.createFromAsset(
				GameResource.tFontOCRAExt, this, "OCRAExt.ttf", 22, true,
				Color.BLACK);

		// airacobra
		GameResource.tFontAiracobra = new BitmapTextureAtlas(128, 128,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		GameResource.mFontAiracobra = FontFactory.createFromAsset(
				GameResource.tFontAiracobra, this, "Airacobra.ttf", 16, true,
				Color.BLACK);

		// allhookedup
		GameResource.tFontAllHookedUp = new BitmapTextureAtlas(128, 128,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		GameResource.mFontAllHookedUp = FontFactory.createFromAsset(
				GameResource.tFontAllHookedUp, this, "AllHookedUp.ttf", 18,
				true, Color.BLUE);

		return true;
	}

	protected boolean loadTexture() {
		// set path
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");

		// character
		// player
		GameResource.tPlayer = new BitmapTextureAtlas(128, 128,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		GameResource.mPlayer = BitmapTextureAtlasTextureRegionFactory
				.createTiledFromAsset(GameResource.tPlayer, this, "hero.png",
						0, 0, 3, 4);

		// ghost
		GameResource.tGhost = new BitmapTextureAtlas(128, 128,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		GameResource.mGhost = BitmapTextureAtlasTextureRegionFactory
				.createTiledFromAsset(GameResource.tGhost, this, "ghost.png",
						0, 0, 4, 4);

		// people
		GameResource.tPeople = new BitmapTextureAtlas(256, 256,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		GameResource.mPeople = BitmapTextureAtlasTextureRegionFactory
				.createTiledFromAsset(GameResource.tPeople, this,
						"indianajones.png", 0, 0, 4, 4);

		// item
		// toilet paper
		GameResource.tToiletPaper = new BitmapTextureAtlas(128, 128,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		GameResource.mToiletPaper = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(GameResource.tToiletPaper, this,
						"toilet_paper.png", 0, 0);

		// control
		// base
		GameResource.tControlBase = new BitmapTextureAtlas(128, 128,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		GameResource.mControlBase = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(GameResource.tControlBase, this,
						"control_base.png", 0, 0);
		// knob di-set 64, supaya gambar tidak terlalu besar (keliatan
		// perseginya)
		GameResource.tControlKnob = new BitmapTextureAtlas(64, 64,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		GameResource.mControlKnob = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(GameResource.tControlKnob, this,
						"control_knob.png", 0, 0);

		GameResource.tBost = new BitmapTextureAtlas(128, 128,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		GameResource.mBost = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(GameResource.tBost, this, "bost.png", 0, 0);

		return true;
	}

	// Semua level dimasukkan disini dan dilempar pada kelas GameResource
	// kedalam list :)
	protected boolean loadLevel() {
		// source tiled map
		GameResource.levelTiledMap.clear();
		for (int i = 1; i <= 10; i++) {
			String level = "level0" + i + ".tmx";
			GameResource.levelTiledMap.add(level);
		}

		// hint
		GameResource.levelHint.clear();
		GameResource.levelHint.add("Tujuan Liburan Pertama MUSIUM \n"
				+ "Cari Pintu Menuju Musium");
		GameResource.levelHint.add("Kamu Sudah Sampai ke Musium,\n"
				+ "Tapi Perut Kamu Tidak Enak dan Harus Mencari Toilet");
		GameResource.levelHint.add("Kamu Terlalu Lama Berada di Toilet, \n"
				+ "Rombongan Tur Sudah Pergi, \n"
				+ "Ayo Segera Keluar Cari Mereka, \n"
				+ "Tapi Jangan Sampai Bertemu Hantu");
		GameResource.levelHint.add("Saatnya Berlibur Dengan Kapal");
		GameResource.levelHint.add("Oh Tidak Perut Mu Sakit, \n"
				+ "Segera Ambil Obat yang Ada di Dalam Kapal");
		GameResource.levelHint.add("Pantai yang Indah, \n"
				+ "Tapi Tujuan Mu adalah Desa");
		GameResource.levelHint.add("Kita Sudah Siap Saatnya Mendaki, \n"
				+ "Kata Orang Desa Kita hanya Jalan Lurus Saja");
		GameResource.levelHint.add("Dimana Teman-Teman Berkemah?");
		GameResource.levelHint
				.add("Argh... Sakit Perut di Malam Hari, \n"
						+ "Tapi Obat Kamu di Desa Sebelumnya\n"
						+ "Ayo Kembali ke Desa");
		GameResource.levelHint.add("Liburan Yang Menyenangkan \n"
				+ "Saatnya Untuk Pulang Dengan Kapal");

		// time
		GameResource.levelTime.clear();
		GameResource.levelTime.add(60);
		GameResource.levelTime.add(90);
		GameResource.levelTime.add(100);
		GameResource.levelTime.add(70);
		GameResource.levelTime.add(40);
		GameResource.levelTime.add(80);
		GameResource.levelTime.add(80);
		GameResource.levelTime.add(80);
		GameResource.levelTime.add(75);
		GameResource.levelTime.add(60);

		return true;
	}

	// Set HighScore
	protected boolean loadHighScore() {
		List<HighScore> listScore = new ArrayList<HighScore>();
		listScore = new HighScoreDAO(getApplicationContext()).gets();

		if (listScore != null) {
			if (listScore.size() == 0) {
				for (int i = 1; i <= GameResource.levelTiledMap.size(); i++) {
					HighScore hScore = new HighScore();

					hScore.setLevel(i);
					hScore.setScore(0);

					new HighScoreDAO(getApplicationContext())
							.insertScore(hScore);
				}
			} else {
				for (int i = listScore.size() + 1; i <= GameResource.levelTiledMap
						.size(); i++) {
					Log.d("level", i + "");
					HighScore hScore = new HighScore();

					hScore.setLevel(i);
					hScore.setScore(0);

					new HighScoreDAO(getApplicationContext())
							.insertScore(hScore);
				}
			}
		} else {
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setIcon(android.R.drawable.ic_dialog_alert);
			alert.setTitle("Error");
			alert.setMessage("Load Highscore Error");
			alert.setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							SplashScreen.this.finish();
						}

					});
			alert.show();
		}

		return true;
	}
}
